package com.chaoxi.picturebackend.aop;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.server.HttpServerRequest;
import com.chaoxi.picturebackend.annotation.AuthCheck;
import com.chaoxi.picturebackend.constant.UserConstant;
import com.chaoxi.picturebackend.exception.BusinessException;
import com.chaoxi.picturebackend.exception.ErrorCode;
import com.chaoxi.picturebackend.model.entity.User;
import com.chaoxi.picturebackend.model.enums.UserRoleEnum;
import com.chaoxi.picturebackend.service.UserService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
public class AuthInterceptor {
    @Resource
    private UserService userService;

    /**
     * 拦截器
     * @param joinPoint 切点
     * @param authCheck 注解
     * @return 拦截结果
     */
    @Around("@annotation(authCheck)")
    public Object doInterceptor(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes)requestAttributes).getRequest();

        // 获取注解中的需要的必要权限
        String mustRole = authCheck.mustRole();
        UserRoleEnum mustRoleEnum = UserRoleEnum.getEnumByValue(mustRole);

        // 获取当前用户
        User loginUser = userService.getLoginUser(request);
        // 不需要权限，放行
        if (mustRoleEnum == null) {
            joinPoint.proceed();
        }

        // 需要权限，判断用户权限
        UserRoleEnum userRoleEnum = UserRoleEnum.getEnumByValue(loginUser.getUserRole());
        if(userRoleEnum == null){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR,"用户无权限");
        }
        // 需管理员权限
        if(mustRoleEnum.equals(UserRoleEnum.ADMIN) && !userRoleEnum.equals(UserRoleEnum.ADMIN)){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR,"用户无管理员权限");
        }
        // 通过身份校验
        return joinPoint.proceed();
    }
}
